package com.pkdl.forms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

import com.pkdl.dao.ThuocDAO;
import com.pkdl.dto.ThuocDTO;
import com.pkdl.tables.TableThuoc;

@SuppressWarnings("serial")
public class DlgQuanLyThuoc extends JDialog {

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DlgQuanLyThuoc dialog = new DlgQuanLyThuoc(null, true);
			dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ThuocDAO thuocDAO;

	private JTable tblData;
	private JTextField txtMaThuoc;
	private JTextField txtTenThuoc;
	private JTextField txtDonViTinh;
	private JTextField txtGia;
	private JTextField txtQuiCach;
	private JTextField txtHamLuong;
	private JTextField txtCachDung;
	private JLabel lblGiaFormated;

	/**
	 * Create the dialog.
	 */
	public DlgQuanLyThuoc(Frame parent, boolean modal) {
		super(parent, modal);
		this.setTitle("Quan ly thuoc");
		this.setBounds(100, 100, 952, 565);
		this.setLocationRelativeTo(null);
		this.getContentPane().setLayout(new BorderLayout());
		{
			JPanel panel = new JPanel();
			this.getContentPane().add(panel, BorderLayout.CENTER);
			panel.setLayout(new BorderLayout(0, 0));
			{
				JPanel panel_1 = new JPanel();
				panel_1.setPreferredSize(new Dimension(452, 10));
				panel.add(panel_1, BorderLayout.WEST);
				panel_1.setLayout(new BorderLayout(0, 0));
				{
					JPanel panel_2 = new JPanel();
					panel_2.setBackground(SystemColor.textHighlight);
					panel_1.add(panel_2, BorderLayout.NORTH);
					panel_2.setLayout(new BorderLayout(0, 0));
					{
						JLabel lblNewLabel = new JLabel(
								"  Danh s\u00E1ch thu\u1ED1c");
						lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
						lblNewLabel.setForeground(Color.WHITE);
						lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
						lblNewLabel.setPreferredSize(new Dimension(46, 32));
						panel_2.add(lblNewLabel, BorderLayout.CENTER);
					}
				}
				{
					JScrollPane scrollPane = new JScrollPane();
					panel_1.add(scrollPane, BorderLayout.CENTER);
					{
						this.tblData = new JTable();
						this.tblData.addMouseListener(new MouseAdapter() {
							@Override
							public void mousePressed(MouseEvent evt) {
								DlgQuanLyThuoc.this.actionSelect(evt);
							}
						});
						this.tblData.setFillsViewportHeight(true);
						this.tblData.setModel(new DefaultTableModel(
								new Object[][] { { null, null, null },
										{ null, null, null },
										{ null, null, null }, }, new String[] {
										"New column", "New column",
										"New column" }));
						scrollPane.setViewportView(this.tblData);
					}
				}
			}
			{
				JPanel panel_1 = new JPanel();
				panel.add(panel_1, BorderLayout.CENTER);
				panel_1.setLayout(null);

				JLabel lblNewLabel_1 = new JLabel("Th\u00F4ng tin thu\u1ED1c");
				lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 18));
				lblNewLabel_1.setForeground(new Color(0, 128, 0));
				lblNewLabel_1.setBounds(10, 0, 287, 31);
				panel_1.add(lblNewLabel_1);

				JLabel lblNewLabel_2 = new JLabel("M\u00E3 thu\u1ED1c");
				lblNewLabel_2.setBounds(34, 57, 63, 14);
				panel_1.add(lblNewLabel_2);

				this.txtMaThuoc = new JTextField();
				this.txtMaThuoc.setEditable(false);
				this.txtMaThuoc.setBounds(118, 54, 86, 20);
				panel_1.add(this.txtMaThuoc);
				this.txtMaThuoc.setColumns(10);
				{
					JLabel lblTnDv = new JLabel("T\u00EAn thu\u1ED1c");
					lblTnDv.setBounds(34, 85, 63, 14);
					panel_1.add(lblTnDv);
				}
				{
					this.txtTenThuoc = new JTextField();
					this.txtTenThuoc.setColumns(10);
					this.txtTenThuoc.setBounds(118, 82, 276, 20);
					panel_1.add(this.txtTenThuoc);
				}
				{
					JLabel lblPhDv = new JLabel(
							"\u0110\u01A1n v\u1ECB t\u00EDnh");
					lblPhDv.setBounds(34, 113, 74, 14);
					panel_1.add(lblPhDv);
				}
				{
					this.txtDonViTinh = new JTextField();
					this.txtDonViTinh.setColumns(10);
					this.txtDonViTinh.setBounds(118, 110, 86, 20);
					panel_1.add(this.txtDonViTinh);
				}
				{
					JLabel lblMT = new JLabel("Gi\u00E1");
					lblMT.setBounds(34, 141, 46, 14);
					panel_1.add(lblMT);
				}

				JButton btnLuu = new JButton("L\u01B0u");
				btnLuu.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						DlgQuanLyThuoc.this.actionLuu();
					}
				});
				btnLuu.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/45.png")));
				btnLuu.setBounds(393, 266, 89, 23);
				panel_1.add(btnLuu);

				JButton btnXa = new JButton("X\u00F3a");
				btnXa.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						DlgQuanLyThuoc.this.actionDelete();
					}
				});
				btnXa.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/001_29.png")));
				btnXa.setBounds(294, 266, 89, 23);
				panel_1.add(btnXa);

				JButton btnThmMi = new JButton("T\u1EA1o m\u1EDBi");
				btnThmMi.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						DlgQuanLyThuoc.this.resetFields();
					}
				});
				btnThmMi.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/Eraser-icon.png")));
				btnThmMi.setBounds(172, 266, 112, 23);
				panel_1.add(btnThmMi);

				this.txtGia = new JTextField();
				this.txtGia.addKeyListener(new KeyAdapter() {
					@Override
					public void keyReleased(KeyEvent ke) {
						char c = ke.getKeyChar();
						if ((!(Character.isDigit(c))) && (c != '\b')) {
							ke.consume();
						} else {
							DlgQuanLyThuoc.this.formatGia();
						}
					}
				});
				this.txtGia.setColumns(10);
				this.txtGia.setBounds(118, 138, 86, 20);
				panel_1.add(this.txtGia);

				JLabel lblQuiCch = new JLabel("Qui c\u00E1ch");
				lblQuiCch.setBounds(34, 169, 74, 14);
				panel_1.add(lblQuiCch);

				this.txtQuiCach = new JTextField();
				this.txtQuiCach.setColumns(10);
				this.txtQuiCach.setBounds(118, 166, 350, 20);
				panel_1.add(this.txtQuiCach);

				JLabel lblHmLng = new JLabel("H\u00E0m l\u01B0\u1EE3ng");
				lblHmLng.setBounds(34, 197, 74, 14);
				panel_1.add(lblHmLng);

				this.txtHamLuong = new JTextField();
				this.txtHamLuong.setColumns(10);
				this.txtHamLuong.setBounds(118, 194, 350, 20);
				panel_1.add(this.txtHamLuong);

				JLabel lblCchDng = new JLabel("C\u00E1ch d\u00F9ng");
				lblCchDng.setBounds(34, 225, 74, 14);
				panel_1.add(lblCchDng);

				this.txtCachDung = new JTextField();
				this.txtCachDung.setColumns(10);
				this.txtCachDung.setBounds(118, 222, 350, 20);
				panel_1.add(this.txtCachDung);

				this.lblGiaFormated = new JLabel("");
				this.lblGiaFormated.setBounds(214, 141, 112, 14);
				panel_1.add(this.lblGiaFormated);
			}
		}
		this.loadData();
	}

	/**
	 * Delete item
	 */
	private void actionDelete() {
		if (this.txtMaThuoc.getText().trim().equals("")) {
			JOptionPane.showMessageDialog(null, "Vui long chon dong de xoa",
					"Announcement", JOptionPane.ERROR_MESSAGE);
			return;
		}
		this.thuocDAO = new ThuocDAO();
		if (this.thuocDAO.delete(Integer.parseInt(this.txtMaThuoc.getText()))) {
			this.loadData();
			this.resetFields();
			JOptionPane.showMessageDialog(null, "Xoa du lieu thanh cong",
					"Announcement", JOptionPane.INFORMATION_MESSAGE);
		} else {
			JOptionPane.showMessageDialog(null, "Khong the xoa du lieu",
					"Announcement", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Them moi, xoa, cap nhat danh sach thuoc
	 */
	private void actionLuu() {
		AtomicReference<Object> errText = new AtomicReference<Object>("");
		if (!this.validateInputData(errText)) {
			JOptionPane.showMessageDialog(null, errText.get(), "Announcement",
					JOptionPane.ERROR_MESSAGE);
			return;
		}

		this.thuocDAO = new ThuocDAO();

		// Them moi
		if (this.txtMaThuoc.getText().trim().equals("")) {
			ThuocDTO thuoc = new ThuocDTO(this.txtDonViTinh.getText(),
					this.txtTenThuoc.getText(), Long.parseLong(this.txtGia
							.getText()), this.txtQuiCach.getText(),
					this.txtHamLuong.getText(), this.txtCachDung.getText());
			if (this.thuocDAO.insert(thuoc)) {
				this.loadData();
				this.resetFields();
				JOptionPane.showMessageDialog(null, "Them du lieu thanh cong",
						"Announcement", JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null, "Khong the them du lieu",
						"Announcement", JOptionPane.ERROR_MESSAGE);
			}
		} else {
			// Cap nhat
			ThuocDTO thuoc = this.thuocDAO.selectById(Integer
					.parseInt(this.txtMaThuoc.getText()));
			thuoc.setTenThuoc(this.txtTenThuoc.getText());
			thuoc.setCachDung(this.txtCachDung.getText());
			thuoc.setDonViTinh(this.txtDonViTinh.getText());
			thuoc.setGia(Long.parseLong(this.txtGia.getText()));
			thuoc.setHamLuong(this.txtHamLuong.getText());
			thuoc.setQuiCach(this.txtQuiCach.getText());
			if (this.thuocDAO.update(thuoc)) {
				this.loadData();
				JOptionPane.showMessageDialog(null,
						"Cap nhat du lieu thanh cong", "Announcement",
						JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null,
						"Khong the cap nhat du lieu", "Announcement",
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Lua chon item trong danh sach
	 */
	private void actionSelect(MouseEvent evt) {
		int modifiers = evt.getModifiers();
		if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
			if (this.tblData.getSelectedRow() == -1) {
				return;
			}

			if (this.tblData.getValueAt(this.tblData.getSelectedRow(), 0) == null) {
				return;
			}

			if (evt.getClickCount() == 1) {
				String mathuoc = ((JLabel) this.tblData.getValueAt(
						this.tblData.getSelectedRow(), 0)).getName().trim();
				this.thuocDAO = new ThuocDAO();
				ThuocDTO thuoc = this.thuocDAO.selectById(Integer
						.valueOf(mathuoc));
				this.txtMaThuoc.setText(String.valueOf(thuoc.getMaThuoc()));
				this.txtTenThuoc.setText(thuoc.getTenThuoc());
				this.txtGia.setText(String.valueOf(thuoc.getGia()));
				this.txtCachDung.setText(thuoc.getCachDung());
				this.txtDonViTinh.setText(thuoc.getDonViTinh());
				this.txtHamLuong.setText(thuoc.getHamLuong());
				this.txtQuiCach.setText(thuoc.getQuiCach());
				this.formatGia();
			}
		}
	}

	/**
	 * Format gia
	 */
	private void formatGia() {
		if (!this.txtGia.getText().trim().equals("")) {
			NumberFormat numberFormatter = new DecimalFormat("#,###,###");
			String formattedNumber = numberFormatter.format(Long
					.parseLong(this.txtGia.getText()));
			this.lblGiaFormated.setText(formattedNumber);
		} else {
			this.lblGiaFormated.setText("");
		}
	}

	/**
	 * Load danh sach thuoc
	 */
	private void loadData() {
		this.thuocDAO = new ThuocDAO();
		List<ThuocDTO> ds = this.thuocDAO.selectAll();
		TableThuoc table = new TableThuoc(ds);
		table.loadDataIntoTable(this.tblData);
	}

	/**
	 * Reset fields
	 */
	private void resetFields() {
		this.txtMaThuoc.setText("");
		this.txtTenThuoc.setText("");
		this.txtDonViTinh.setText("");
		this.txtCachDung.setText("");
		this.txtHamLuong.setText("");
		this.txtQuiCach.setText("");
		this.txtGia.setText("");
		this.lblGiaFormated.setText("");
	}

	/**
	 * Validate user input
	 * 
	 * @return true: valid / false: invalid
	 */
	private boolean validateInputData(AtomicReference<Object> errText) {
		if (this.txtTenThuoc.getText().trim().equals("")) {
			errText.set("Ban chua nhap ten thuoc");
			return false;
		}
		if (this.txtGia.getText().trim().equals("")) {
			errText.set("Ban chua nhap gia thuoc");
			return false;
		}
		return true;
	}
}
